import { Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { NzModalRef, NzMessageService, UploadFile } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CacheService } from '@core/routes-services/cache.service';
import { ImgMaterialService } from '@core/routes-services/img-material.service';
import { QCLOUD_DOMAIN, UPLOAD_DOMAIN } from '../../../constant/config';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { QcloudService } from '@core/routes-services/qcloud.service';
import { ImgMaterialTypeService } from '@core/routes-services/img-material-type.service';

@Component({
  selector: 'app-img-material-img-material-edit',
  templateUrl: './img-material-edit.component.html',
  styles: [`
    :host ::ng-deep .ant-upload-select-picture-card {
      width: 128px;
      height: 128px;
    }

    :host ::ng-deep .ant-upload-select-picture-card i {
      font-size: 32px;
      color: #999;
    }

    :host ::ng-deep .ant-upload-select-picture-card .ant-upload-text {
      margin-top: 8px;
      color: #666;
    }

    :host ::ng-deep .ant-upload .avatar {
      width: 120px;
      height: 120px;
    }
  `],
})
export class ImgMaterialEditComponent implements OnInit, OnDestroy {

  id: number = 0;
  entity: any = {};
  origin: any = 1;
  validateForm: FormGroup;
  isLoading: boolean = false;

  uploadDomain = UPLOAD_DOMAIN;
  qcloudDomain = QCLOUD_DOMAIN;
  headers: any = {};

  typeOptions: any [] = [];
  componentDirty: boolean = false;
  @ViewChild('content') content: ElementRef;

  cos: any; // 腾讯云实例对象
  Bucket = 'telun-1256143479'; //存储桶
  Region = 'ap-guangzhou'; // 所属地域

  constructor(private fb: FormBuilder,
              private router: Router,
              private route: ActivatedRoute,
              private imgMaterialService: ImgMaterialService,
              private imgMaterialTypeService: ImgMaterialTypeService,
              private cacheService: CacheService,
              private qcloudService: QcloudService,
              public message: NzMessageService,
  ) {
  }


  ngOnInit(): void {
    this.initOptions();
    const token: any = this.cacheService.getTokenInfo();
    this.headers = { 'Authorization': token };
    this.route.params.forEach((params) => {
      this.origin = +params['origin'];
    });
    this.route.queryParams.forEach((params: Params) => {
      this.id = +params['id'];
      this.initEntity();
    });
    this.initValidateForm();
    this.initCos();
  }

  initOptions() {
    this.imgMaterialTypeService.getAll().then((res) => {
      if (res.status.toString().startsWith('20')) {
        this.typeOptions = res.data.imgMaterialTypeList;
      } else {
        this.message.warning(res.message);
      }
    }, error => {
      this.message.error(error.message ? error.message : error.error);
    });
  }

  initCos() {
    //参考文档：https://cloud.tencent.com/document/product/436/11459
    const that = this;
    this.cos = new COS({
      getAuthorization: function(options, callback) {
        that.qcloudService.buildAuthorizationStr().then((res: any) => {
            let authObj = JSON.parse(res.data);
            callback({
              TmpSecretId: authObj.data.credentials.tmpSecretId,
              TmpSecretKey: authObj.data.credentials.tmpSecretKey,
              XCosSecurityToken: authObj.data.credentials.sessionToken,
              ExpiredTime: authObj.data.expiredTime,
              // Authorization: res.Authorization,
              // XCosSecurityToken: res.XCosSecurityToken, // 如果是临时密钥计算出来的签名，需要提供 XCosSecurityToken
            });
          },
        );
      },
    });
  }


  initEntity() {
    if (this.id != 0) {
      this.imgMaterialService.detail(this.id).then((res) => {
        if (res.status.toString().startsWith('20')) {
          this.entity = res.data;
          this.videoList = this.entity.videoList;
          this.initValidateForm();
        } else {
          this.message.warning(res.message);
        }
        this.isLoading = false;
      }, error => {
        this.message.error(error.message ? error.message : error.error);
        this.isLoading = false;
      });
    }
  }

  initValidateForm() {
    this.validateForm = this.fb.group({
      origin: [this.origin, [Validators.required]],
      type: [this.entity.type, [Validators.required]],
      title: [this.entity.title, [Validators.required, Validators.maxLength(60)]],
      videoKey: [this.entity.videoKey, []],
      videoInfos: [this.entity.videoInfos, []],
      mainImg: [this.entity.mainImg, [Validators.required]],
      sortNum: [this.entity.sortNum, [Validators.required]],
      description: [this.entity.description, [Validators.required]],
    });

    this.content.nativeElement.innerHTML = this.entity.description ? this.entity.description : '点击进行内容编辑';
  }


  isShow: boolean = false;

  showEdit() {
    this.isShow = !this.isShow;
    let body = document.body;
    if (this.isShow) {
      body.style.overflow = 'hidden';
      body.style.userSelect = 'none';
    } else {
      body.style.overflow = '';
      body.style.userSelect = '';
    }
  }

  contentCallback(content) {
    this.entity.description = content;
    this.content.nativeElement.innerHTML = this.entity.description;
    this.componentDirty = true;
    this.validateForm.controls.description.setValue(content);
  }

  submitForm(): void {
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {
      //保存修改
      if (this.validateForm.dirty || this.componentDirty) {
        this.isLoading = true;
        console.log(this.validateForm.value);
        this.imgMaterialService.saveOrUpdateEntity(this.entity.id, this.validateForm.value).then((res) => {
          if (res.status.toString().startsWith('20')) {
            this.componentDirty = false;
            this.initValidateForm();
            this.goBack();
          } else {
            this.message.warning(res.message);
          }
          this.isLoading = false;
        }, error => {
          this.message.error(error.message ? error.message : error.error);
          this.isLoading = false;
        });
      } else {
        //无操作直接返回
        this.goBack();
      }
    }
  }

  goBack() {
    this.router.navigate(['img-material/list/' + this.origin]);
  }

  /**
   * 上传图控件 ng-zorro upload
   *
   * @param {any} file
   * @param {any} fileList
   */
  handleChange({ file, fileList }): void {
    const status = file.status;
    if (status !== 'uploading') {
      // console.log(file, fileList);
    }
    if (status === 'done') {
      this.message.success(`${file.name} 上传成功`);
      let findIdx = fileList.findIndex(w => file.lastModified == w.lastModified);
      fileList[findIdx].imgKey = fileList[findIdx].response.data;
      fileList[findIdx].name = fileList[findIdx].response.data;
      fileList[findIdx].url = this.qcloudDomain + fileList[findIdx].response.data;
      this.entity.mainImg = fileList[findIdx].url;
      this.validateForm.controls.mainImg.setValue(this.entity.mainImg);
      this.componentDirty = true;
    } else if (status === 'error') {
      this.message.error(`${file.name} 上传失败`);
    }
  }



  videoList: any[] = [];
  btnText: any = '添加视频';
  uploading: boolean = false;
  beforeUpload = (file: UploadFile): boolean => {
    if (this.uploading) {
      this.message.warning('文件正在上传中');
      return false;
    }
    const that = this;
    const originName = file.name;
    const name = 'video/' + new Date().getTime() + originName.substr(originName.lastIndexOf('.'));
    this.cos.putObject({
      Bucket: that.Bucket,
      Region: that.Region,
      Key: name,
      Body: file,
      onProgress: function(progressData) {
        that.uploading = true;
        console.log('上传中================' + name);
        // console.log(JSON.stringify(progressData));
        that.btnText = '视频上传中，进度：' + (progressData.percent * 100).toFixed(2) + '%（' + (progressData.speed / 1024).toFixed(2) + 'kb/s）';
      },
    }, function(err, data) {
      that.uploading = false;
      that.btnText = '添加视频';
      if (err) {
        console.log('上传失败================' + name);
        console.log(err);
        that.message.error('上传失败，请刷新页面重试');
      } else {
        console.log('上传成功================' + name);
        that.componentDirty = true;
        that.videoList.push({ videoName: originName, videoKey: that.qcloudDomain + name });
        that.validateForm.controls.videoInfos.setValue(JSON.stringify(that.videoList));
      }
    });
    return false;
  };

  deleteFile(index) {
    let that = this;
    // 可能删了又不保存 后续处理
    // console.log(that.entity.videoKey)
    // let key  = that.validateForm.controls.videoKey.value.toString().replace(that.qcloudDomain,"");
    // console.log(key);
    // this.qcloudService.deleteFileByKey(key).then((res)=>{
    //   console.log(res);
    that.videoList.splice(index, 1);
    that.componentDirty = true;
    that.validateForm.controls.videoInfos.setValue(JSON.stringify(that.videoList));
    // },error=>{
    //   console.log(error);
    // })
  }

  ngOnDestroy(): void {
    this.cos = null;
  }


  /*********************************useless***************************************/
  toStop() {
    document.getElementById('uploadVideo').setAttribute('type', 'text');
    document.getElementById('uploadVideo').setAttribute('type', 'file');
  }

  onAfterSelect(event: any) {
    let files = event.target.files;
    // console.log(files)
    // console.log(event)
    for (let i = 0; i < files.length; i++) {//其实只一个
      let file: any = files[i];
      if (this.uploading) {
        this.message.warning('文件正在上传中');
        return false;
      }
      const that = this;
      const originName = file.name;
      const name = 'video/' + new Date().getTime() + originName.substr(originName.lastIndexOf('.'));
      this.cos.putObject({
        Bucket: that.Bucket,
        Region: that.Region,
        Key: name,
        Body: file,
        onProgress: function(progressData) {
          that.uploading = true;
          console.log('上传中================' + name);
          // console.log(JSON.stringify(progressData));
          that.btnText = '视频上传中，进度：' + progressData.percent * 100 + '%（' + (progressData.speed / 1024).toFixed(2) + 'kb/s）';
        },
      }, function(err, data) {
        that.uploading = false;
        if (err) {
          console.log('上传失败================' + name);
          console.log(err);
          that.message.error('上传失败，请刷新页面重试');
        } else {
          console.log('上传成功================' + name);
          that.componentDirty = true;
          that.entity.videoKey = that.qcloudDomain + name;
          that.entity.videoName = originName;
          that.validateForm.controls.videoKey.setValue(that.entity.videoKey);
          that.validateForm.controls.videoName.setValue(that.entity.videoName);
        }
      });
    }
  }


}
